from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client

@deconstructible
class FastDFSStorage(Storage):
    def __init__(self, base_url=None, client_conf=None):
        self.client_conf = client_conf or settings.FDFS_CLIENT_CONF
        self.base_url = base_url or settings.FDFS_BASE_URL
    def _open(self, name, mode='rb'):
        pass
    def _save(self, name, content):
        '''file_id 自动存储在模型类ImageField字段中'''
        client = Fdfs_client(self.client_conf)
        ret = client.upload_by_buffer(content.read())

        if ret.get('Status') != 'Upload successed.':
            raise Exception('fastfds upload failed')

        file_id = ret.get('Remote file_id')
        return file_id

    def exists(self, name):
        return False
    def url(self, name):
        return self.base_url + name